export default function applyMiddleware(...middlewares) {
  return createStore => reducer => {
    const store = createStore(reducer)
    let dispatch = store.dispatch // 原始 dispatch
    // 加强diapatch
    // 原先的diaptch只能处理 object， 加强只有要能处理函数 promise等...
    const midApi = {
      getState: store.getState,
      dispatch: (action, ...agrs) => dispatch(action, ...agrs) // 避免dispatch污染，所有使用函数返回
    }
    const middlewareChain = middlewares.map(middleware => middleware(midApi))
    // middlewareChain中间件数组
    // 按照顺序执行中间件函数
    dispatch = compose(...middlewareChain)(store.dispatch) // 加强版的disptch

    return {
      ...store,
      dispatch,
    }
  }
}

function compose(...funcs) {
  if(funcs.length === 0) {
    return arg => arg
  }
  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}